package com.ist.neartweat;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.ist.neartweat.messages.Message;
import com.ist.neartweat.messages.NewTweatMessage;
import com.ist.neartweat.messages.NewTweatUpdateMessage;
import com.ist.neartweat.messages.PrivateMessage;
import com.ist.neartweat.messages.RegistartionSuccessMessage;
import com.ist.neartweat.messages.ReplyMessage;
import com.ist.neartweat.platForm.Tweat;
import com.ist.neartweat.service.NetworkService;
import com.ist.neartweat.service.NetworkService.NetBinder;

public class SecondActivity extends Activity {
	NetworkService mService;
	boolean mBound = false;
	ArrayList<Message> msgs = new ArrayList<Message>();
	boolean readLoop = true;
	ArrayList<Tweat> tweats=null ;
	ArrayList<String> tweatStrings=new ArrayList<String>();
	ArrayAdapter<String> tweatAdapter;
	String ClientId;
	SecondActivity myself = this;
	MyHandler hdlr ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);
		Intent intent = new Intent(this, NetworkService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

		Intent it  = getIntent();
		this.ClientId= it.getStringExtra("com.ist.nearTweat.ClientId");
		
		hdlr= new MyHandler();		
				startThread(hdlr);
	}
	@Override
	protected void onStart() {
		super.onStart();
		// Bind to LocalService
		System.out.println("2nd Act");
		/*Start the thread to read messages from the NetworkService */


		System.out.println("2nd Act Thd Ext");

		ListView tweatListView = (ListView) findViewById(R.id.tweatViewID);
		//ArrayList<String> tweatStrings1 = new ArrayList<String>();tweatStrings1.add("item1");tweatStrings1.add("item2");tweatStrings1.add("item3");
		tweatAdapter = new ArrayAdapter<String>(this,R.layout.tweatitem ,tweatStrings);
		tweatListView.setAdapter(tweatAdapter);
		//tweatStrings.add("New String added");
		//tweatAdapter.notifyDataSetChanged();

		//itemListener  listener = new itemListener(this);
		tweatListView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int arg2,
					long arg3) {
				System.out.println("OnItemListnere Started");
				Intent intent = new Intent(myself, TweatDetailsActivity.class);
				Tweat t = getTweatWithId(((TextView) v).getText().toString());
				intent.putExtra("com.ist.neartweat.ClientID",ClientId);
				intent.putExtra("com.ist.neartweat.Tweat", t);
				startActivity(intent);
				System.out.println("OnItemListnere creation ended");
			}

		});


	}
	
	protected void onReusme(){
		hdlr.post(new Runnable(){
			public void run(){
				tweatAdapter.notifyDataSetChanged();
			}
		});
		 super.onResume();
	}

	public void startThird(View v){
		System.out.println("OnItemListnere Started");
		EditText editText = (EditText) findViewById(R.id.tweatID);
		String tweatId = editText.getText().toString();
		Intent intent = new Intent(myself, TweatDetailsActivity.class);
		Tweat t = getTweatWithId(tweatId);
		intent.putExtra("com.ist.neartweat.TweatDetailsTimeStamp",System.currentTimeMillis());
		intent.putExtra("com.ist.neartweat.ClientID",ClientId);
		intent.putExtra("com.ist.neartweat.Tweat", t);
		startActivity(intent);
		System.out.println("OnItemListnere creation ended");
	}

	public void startPollActivity(View v){
		System.out.println("PollActivity creation Started");
		Intent intent = new Intent(myself, PollActivity.class);
		intent.putExtra("com.ist.neartweat.ClientID", ClientId);
		startActivity(intent);
		System.out.println("PollActivity creation ended");
	}

	public void startTweatActivity(View v){
		System.out.println("TweatActivity creation Started");
		Intent intent = new Intent(myself, TweatActivity.class);
		intent.putExtra("com.ist.neartweat.ClientID", ClientId);
		startActivity(intent);
		System.out.println("TweatActivity creation ended");
	}

	public class itemListener implements OnItemClickListener{
		SecondActivity secondActivity;
		public itemListener(SecondActivity secondActivity) {
			this.secondActivity = secondActivity;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int arg2,
				long arg3) {

			Intent intent = new Intent(this.secondActivity, TweatDetailsActivity.class);
			Tweat t = getTweatWithId(((TextView) v).getText().toString());
			intent.putExtra("com.ist.neartweat.ClientID",ClientId);
			intent.putExtra("com.ist.neartweat.Tweat", t);
			startActivity(intent);
		}

	}


	/*This thread reads messages from the Network Service */
	public void startThread(final Handler hdlr){
		System.out.println("New Thread Start");
		new Thread(){
			public void run(){
				while(!mBound){

				}
				System.out.println("From Thread. Now reading Messages Since Service connected");
				while(readLoop){
					ArrayList<Message> al= mService.giveMsgs();
					if(al!=null){
						System.out.println("2nd Act received message"+al.size());
						for(Message m : al){
							handleMessage(m,hdlr);
						}
						msgs.addAll(al);
					}

					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}.start();
		System.out.println("New Thread Start completed");
	}
	
	@Override
	public void onBackPressed (){
		readLoop =false;
		mService.unbindService(mConnection);
	finish();
	}

	public Tweat getTweatWithId(String text) {
		for(Tweat t :tweats){
			if(t.getTweatId().equals(text)){
				return t;
			}
		}
		return null;
	}
	public void handleMessage(Message msg, Handler hdlr){
		if(msg instanceof RegistartionSuccessMessage){
			System.out.println("Received RegistrationSuccess Message");
			RegistartionSuccessMessage rms = (RegistartionSuccessMessage)msg;
			this.tweats = rms.getTweats();
			System.out.println("The received tweat size is "+rms.getTweats().size());
			try{
				for(Tweat t: tweats){
					tweatStrings.add(t.getTweatId()+"->"+t.getTweatString());
					System.out.println("Tweat String ::"+t.getTweatId()+"->"+t.getTweatString());
				}

				hdlr.post(new Runnable(){
					public void run(){
						tweatAdapter.notifyDataSetChanged();
					}
				});
			}
			catch(Exception e){
				System.out.println("Exception in RegistrationSuccess");
				e.printStackTrace();
			}

		}
		else if(msg instanceof ReplyMessage){
			ReplyMessage rm = (ReplyMessage)msg;
			String tweatId= rm.getTweatId();
			Tweat twet = getTweatWithId(tweatId);
			if(rm.isPrivate()){
				twet.addPvtReply(rm.getR());
			}
			else{
				twet.addPubReply(rm.getR());
			}
			
		}
		
		else if(msg instanceof NewTweatUpdateMessage){
			NewTweatUpdateMessage ntum = (NewTweatUpdateMessage)msg;
			Tweat t = ntum.getTweat();
			if(this.tweats!=null){
				this.tweats.add(t);
			}
			else{
				this.tweats = new ArrayList<Tweat>();
				this.tweats.add(t);
			}
			this.tweatStrings.add(t.getTweatId()+"->"+t.getTweatString());
			System.out.println("Tweat String ::"+t.getTweatId()+"->"+t.getTweatString());
			//notifiy the tweatAdapter;
			hdlr.post(new Runnable(){
				public void run(){
					tweatAdapter.notifyDataSetChanged();
				}
			});
		}
		
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.second, menu);
		return true;
	}
	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName className,
				IBinder service) {
			// We've bound to LocalService, cast the IBinder and get LocalService instance
			System.out.println("Connected to the service from second activity");
			NetBinder binder = (NetBinder) service;
			mService = binder.getService();
			mBound = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mBound = false;
		}
	};

	public void SendMsg(View view){
		try {
			mService.sendMsg(new PrivateMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("Exception while Sendming Message from Second Activity");
			e.printStackTrace();
		}
	}
	static class MyHandler extends Handler{
		public void HandleMessage(){

		}
	}
}


